using System.Collections.Generic;
using UnityEngine;

public class ManagerScrollMissions : MonoBehaviour
{
	public static ManagerScrollMissions instance;

	private List<MissionBase> missionsList = new List<MissionBase>();

	private List<ButScrollMission> listButton = new List<ButScrollMission>();

	public ButScrollMission exampleBut;

	public GameObject parentButton;

	private UIGrid gridScript;

	private void Awake()
	{
		instance = this;
	}

	private void OnDestroy()
	{
		instance = null;
	}

	private void OnEnable()
	{
		Invoke("UpdateListMissions", 0.03f);
	}

	public void UpdateListMissions()
	{
		if (gridScript == null)
		{
			gridScript = parentButton.GetComponent<UIGrid>();
		}
		missionsList = ManagerMissions.instance.startedMission;
		if (BCWDebug.isDebugBuild)
		{
		}
		SetButtonCount(missionsList.Count);
		for (int i = 0; i < listButton.Count; i++)
		{
			ButScrollMission butScrollMission = listButton[i];
			butScrollMission.SetInfoMission(missionsList[i]);
		}
		Sort();
		Invoke("Sort", 0.2f);
	}

	private void Sort()
	{
		if (gridScript != null)
		{
			gridScript.repositionNow = true;
		}
	}

	private void SetButtonCount(int needCount)
	{
		if (listButton.Count < needCount)
		{
			for (int i = listButton.Count; i < needCount; i++)
			{
				if (BCWDebug.isDebugBuild)
				{
					BCWDebug.Log("add button at " + i);
				}
				ButScrollMission item = CreateButton();
				listButton.Add(item);
			}
		}
		else if (listButton.Count > needCount)
		{
			int num = listButton.Count - needCount;
			for (int j = 0; j < num; j++)
			{
				if (BCWDebug.isDebugBuild)
				{
					BCWDebug.Log("remove button at " + (listButton.Count - 1));
				}
				GameObject obj = listButton[listButton.Count - 1].gameObject;
				listButton[listButton.Count - 1] = null;
				listButton.RemoveAt(listButton.Count - 1);
				Object.Destroy(obj);
			}
		}
		if (needCount > 0)
		{
			ManagerHUDMissionLobby.instance.labelJobs.SetActive(true);
		}
		else
		{
			ManagerHUDMissionLobby.instance.labelJobs.SetActive(false);
		}
	}

	private ButScrollMission CreateButton()
	{
		GameObject gameObject = Object.Instantiate(exampleBut.gameObject, Vector3.zero, Quaternion.identity) as GameObject;
		gameObject.SetActive(true);
		ButScrollMission component = gameObject.GetComponent<ButScrollMission>();
		component.iconMission.spriteName = string.Empty;
		component.lbTitleMission.text = string.Empty;
		gameObject.transform.parent = parentButton.transform;
		gameObject.transform.localScale = new Vector3(1f, 1f, 1f);
		return component;
	}
}
